package com.zgzg.shop.pay.base.utils.lambda;

import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.reflection.property.PropertyNamer;

import java.util.ArrayList;
import java.util.List;

/**
 * 通过lambda属性表达式工具类
 * {@link <a>https://gitee.com/joker-pper/mybatis-plus-query.git</a>}
 */
public class LambdaPropertyUtils {

    public static <T> List<String> getPropertyList(SFunction<T, ?>... propertyFunctions) {
        List<String> propertyList = new ArrayList<String>(16);
        if (propertyFunctions != null) {
            for (SFunction propertyFunction : propertyFunctions) {
                propertyList.add(getProperty(propertyFunction));
            }
        }
        return propertyList;
    }

    public static <T> String[] getProperties(SFunction<T, ?>... propertyFunctions) {
        List<String> propertyList = getPropertyList(propertyFunctions);
        return propertyList.toArray(new String[propertyList.size()]);
    }

    public static <T> String getProperty(SFunction<T, ?> propertyFunction) {
        LambdaMeta extract = LambdaUtils.extract(propertyFunction);
        return PropertyNamer.methodToProperty(extract.getImplMethodName());
    }

    public static <T> List<String> getColumnList(SFunction<T, ?>... propertyFunctions) {
        return getColumnList(null, propertyFunctions);
    }

    public static <T> List<String> getColumnList(Class entityClass, SFunction<T, ?>... propertyFunctions) {
        if (propertyFunctions != null && propertyFunctions.length > 0) {
            List<String> propertyList = getPropertyList(propertyFunctions);
            if (entityClass == null) {
                LambdaMeta extract = LambdaUtils.extract(propertyFunctions[0]);
                entityClass = extract.getInstantiatedClass();
            }
            return QuerySupportUtils.getColumnList(entityClass, propertyList.toArray(new String[propertyList.size()]));
        }
        return new ArrayList<String>();
    }

    public static <T> String[] getColumns(Class entityClass, SFunction<T, ?>... propertyFunctions) {
        List<String> columnList = getColumnList(entityClass, propertyFunctions);
        return columnList.toArray(new String[columnList.size()]);
    }

    public static <T> String[] getColumns(SFunction<T, ?>... propertyFunctions) {
        List<String> columnList = getColumnList(propertyFunctions);
        return columnList.toArray(new String[columnList.size()]);
    }

    public static <T> String getColumn(SFunction<T, ?> propertyFunction) {
        LambdaMeta extract = LambdaUtils.extract(propertyFunction);
        String property = PropertyNamer.methodToProperty(extract.getImplMethodName());
        return QuerySupportUtils.getColumn(extract.getInstantiatedClass(), property);
    }

}
